package com.lottoad.android.activity.info;

import java.util.ArrayList;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lottoad.android.R;
import com.lottoad.android.common.BaseActivity;

public class LottoAdInfoRecommenderActivity extends BaseActivity {
	
	private Context mContext;
	private final String BASE_URL = "http://ad.lcdns.kr/server/findManager.asp?ManagerId=";
	private final String RESULT_SUCCESS = "SUCCESS";
	private final String RESULT_FAIL = "FAIL";
	
	private Button mDoneButton, mCheckRecommenderIdButton;
	private EditText mRecommenderId;
	private TextView mDesctiptionTextView;
	
	// 추천인 확인버튼이 Validate상태인지 확인하는 flag
	private boolean mIsValidateButtonEnabled = false;
	// 추천인 ID 확인이 됐는지 여부 체크하는 flag
	private boolean mIsRecommenderIdValidated = false;
	// 확인된 추천인 ID를 저장하는 String
	private String mValidatedId = "";
	// 텍스트가 보여지는지여부 체크 flag
	private boolean mIsDescriptionShown = false;
	
	
	@Override
	protected int onGetContentViewResource() {
		return R.layout.lottoad_info_recommender;
	}
	
	
	@Override
	protected void onInit() {
		setContentView(R.layout.lottoad_info_recommender);
		
		mContext = this;
		
		initViews();
	}
	
	public void initViews() {
		mDoneButton = (Button) findViewById(R.id.btn_recommender_done);
		mRecommenderId = (EditText) findViewById(R.id.et_recommender_number);
		
		mRecommenderId.addTextChangedListener(new TextWatcher() {
			@Override
			public void afterTextChanged(Editable s) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,	int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
				if(mIsRecommenderIdValidated) {
					// 확인 절차가 끝났는데 바꾼 경우이므로 이전 확인 절차여부 초기화
					mIsRecommenderIdValidated = false;
					mValidatedId = "";
					mDesctiptionTextView.setText(getResources().getString(R.string.require_id_validate_text));
				}
				
				if(s.toString().length() == 4) { 
					// 숫자가 하나라도 들어간 경우 설명 보여주고 버튼 활성화
					if(!mIsValidateButtonEnabled) {
						setValidateButtonEnabled(true);
					}
					
					if(!mIsDescriptionShown) {
						showDescription(true);
					}
					
				} else {
					// 내용이 없는 경우 버튼 비활성화 및 설명 지움.
					setValidateButtonEnabled(false);
					showDescription(false);
				}
				
			}		
		});
		
		
		
		
		mDoneButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(mRecommenderId.getText().length() == 0) {
					// 추천인 입력하지 않은경우
					new AlertDialog.Builder(mContext).setTitle(R.string.popup_alert).
					setMessage(R.string.no_recommender_warning).
					setPositiveButton(R.string.btn_title_yes, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							finishWithResult();
						}
					}).
					setNegativeButton(R.string.btn_title_no, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}).show();
					
				} else {
					if(mRecommenderId.getText().length() == 4) {
						// 자릿수 체크
						finishWithResult();
					} else {
						// 차릿수가 맞지 않는 경우
						new AlertDialog.Builder(mContext).setTitle(R.string.popup_alert).
						setMessage(R.string.check_recommender_id).
						setPositiveButton(R.string.commons_ok, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						}).show();
					}
				}
				
			
			}
		});
		
		mDesctiptionTextView = (TextView) findViewById(R.id.tv_recommender_id_valid_text);
		mCheckRecommenderIdButton = (Button) findViewById(R.id.btn_recommender_validate);
		mCheckRecommenderIdButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO: 추천인 아이디 체크 버튼..
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
				onRequestData();
			}
		});
	}
	
	public void setValidateButtonEnabled(boolean isEnable) {
		mIsValidateButtonEnabled = isEnable;
		mCheckRecommenderIdButton.setEnabled(isEnable);
	}
	
	public void showDescription(boolean isShow) {
		mIsDescriptionShown = isShow;
		if(isShow) {
			mDesctiptionTextView.setVisibility(View.VISIBLE);
		} else {
			mDesctiptionTextView.setVisibility(View.GONE);
		}
	}
	
	@Override
	public void onBackPressed() {
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(mRecommenderId.getWindowToken(), 0);
		
		super.onBackPressed();
	}
	
	public void finishWithResult() {
		
		Log.d("BenTag", "Recommender : " + mValidatedId);
		Intent data = new Intent();
		if(mIsRecommenderIdValidated) {
			data.putExtra("recommenderId", mValidatedId);
		}
		setResult(RESULT_OK, data);
		finish();
	}

	@Override
	public void onAsyncPreRequest() {
		super.showLoadingDialog(R.string.checking);
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject) {
		super.hideLoadingDialog();
		parseJobList(xmlObject);
	}

	@Override
	public void onAsyncCancelRequest() {
		super.hideLoadingDialog();
	}

	@Override
	public String onGetAsyncRequestUrl() {
		return BASE_URL + "AL" + mRecommenderId.getText().toString();
	}

	@Override
	public void onAsyncRequestError(int paramInt) {
		super.hideLoadingDialog();
	}

	@Override
	public void onAsyncDataError(Element paramXMLObject, String paramString) {
		super.hideLoadingDialog();
	}
	
	private void parseJobList(Element xmlObject) {
		String result = RESULT_FAIL;
		try {
			NodeList returnCodeList = xmlObject.getElementsByTagName("rcode");
			
			result = returnCodeList.item(1).getFirstChild().getNodeValue();
			/*if(returnCodeList != null) {
				int count = returnCodeList.getLength();
				Log.i("BenTag", "########################################################################");
				for(int i = 0; i < count; i++) {
					String content = returnCodeList.item(i).getFirstChild().getNodeValue();
					Log.i("BenTag", content);
				}
				Log.i("BenTag", "########################################################################");
			}*/
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		if(result.equals(RESULT_FAIL)) {
			showFailDialog();
		} else {
			if(result.equals(RESULT_SUCCESS)) {
				mIsRecommenderIdValidated = true;
				setValidateButtonEnabled(false);
				mValidatedId = "AL" + mRecommenderId.getText().toString();
				mDesctiptionTextView.setText(getResources().getString(R.string.recommender_id_validated_text));
			}
		}
	}
	
	private void showFailDialog() {
		AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
		dialog.setTitle(R.string.popup_alert).
		setMessage(R.string.not_valid_recommender_id).
		setPositiveButton(R.string.commons_ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				mRecommenderId.setText("");
			}
		}).show();
	}

	

	
	
}
